//
//  GroupDetailVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/24.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "GroupDetailVC.h"
#import "GroupUserCell.h"
#import "MineCell.h"
#import "EVCPopInputView.h"
#import "ZXConfirmButton.h"
#import "YBApiManager+Chat.h"
#import <LKDBHelper/LKDBHelper.h>
#import "FriendInfoListVC.h"
#import "GroupUserListVC.h"
#import "AddressListVC.h"
#import "BaseNavigationController.h"
#import "GroupUserListVC.h"
#import "MyQRCodeVC.h"
#import "MsgItem.h"
#import "SessionItem.h"
#import "GroupManagerVC.h"
#import "SwitchCell.h"
#import "CacheHelper.h"
#import "SearchMsgVC.h"

@interface GroupDetailVC ()
@property (nonatomic, strong) ZXConfirmButton *quitBtn;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation GroupDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupDataSource];
    [self requestDatas];
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_GroupChatInfo_updated object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self requestDatas];
    }];
}

- (void)setupUI {
    self.title = @"详情";
    [self.tableView customRegisterClassWithName:@"GroupUserCell"];
    [self.tableView customRegisterClassWithName:@"MineCell"];
    [self.tableView customRegisterClassWithName:@"SwitchCell"];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = UIColor.clearColor;
    
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 300, ScreenWidth, 65+20)];
    bottomView.backgroundColor = UIColor.clearColor;
    self.quitBtn = [ZXConfirmButton confirmButton];
    self.quitBtn.k_title(@"删除并退出");
    self.quitBtn.frame = CGRectMake(50, 30, ScreenWidth-100, 40);
    [self.quitBtn addTarget:self action:@selector(didClickBottomBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.quitBtn];
    self.tableView.tableFooterView = bottomView;
    self.bottomView = bottomView;
}
- (void)setupDataSource {
    [self.dataSource removeAllObjects];
    
    YBContentModel *model = YBContentModel.new;
    model.cellId = @"GroupUserCell";
    [self.dataSource addObject:model];
    
    NSArray *dataArr = @[
                         @{@"title": @"群聊名称",
                           @"rightText": self.group.name?:@"",
                           @"icon": @"",
                           @"vc": @"",
                           @"cellId": @"MineCell"
                           },
                         @{@"title": @"群号和二维码",
                           @"rightText": @"",
                           @"icon": @"arrow_right",
                           @"vc": @"",
                           @"cellId": @"MineCell"
                           },
                         @{@"title": @"查找聊天内容",
                           @"rightText": @"",
                           @"icon": @"arrow_right",
                           @"vc": @"",
                           @"cellId": @"MineCell"
                           },
                         @{@"title": @"消息免打扰",
                           @"rightText": @"",
                           @"icon": @"",
                           @"vc": @"",
                           @"cellId": @"SwitchCell",
                           @"selected": @(self.group.no_disturb)
                           },
                         @{@"title": @"清空聊天记录",
                           @"rightText": @"",
                           @"icon": @"arrow_right",
                           @"vc": @"",
                           @"cellId": @"MineCell"
                           },
//                         @{@"title": @"设置",
//                           @"rightText": @"",
//                           @"icon": @"arrow_right",
//                           @"vc": @""
//                           }
                         ];
    
    NSMutableArray *models = [YBContentModel mj_objectArrayWithKeyValuesArray:dataArr];
    [self.dataSource addObjectsFromArray:models];
    
    if (self.group.manager == YES) {
        YBContentModel *model = YBContentModel.new;
        model.title = @"群管理";
        model.icon = @"arrow_right";
        model.cellId = @"MineCell";
        [self.dataSource insertObject:model atIndex:4];
    }
    
    [self.tableView reloadData];
}

- (void)requestDatas {
    
    [[YBApiManager.shareManager groupInfoWithGroupId:self.group.group_id] subscribeNext:^(id  _Nullable x) {
        NSDictionary *dataDic = [x objectForKey:@"data"];
        [self.group mj_setKeyValues:dataDic];
        [self.group updateToDB];
        [self setupDataSource];
    } error:^(NSError * _Nullable error) {
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YBContentModel *model = self.dataSource[indexPath.row];
    @weakify(self);
    GroupUserCell *cell = [tableView dequeueReusableCellWithIdentifier:model.cellId forIndexPath:indexPath];
    cell.showBottomLine = YES;
    if (indexPath.row > 0) {
        MineCell *mCell = (MineCell *)cell;
        mCell.model = model;
        if ([cell isKindOfClass:SwitchCell.class] == YES) {
            SwitchCell *sCell = (SwitchCell *)cell;
            [[[sCell.switchView rac_newOnChannel] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(NSNumber * _Nullable x) {
                NSLog(@"x = %@",x);
                @strongify(self);
                [self didClickSwitchViewAction:sCell.switchView indexPath:indexPath];
            }];
        }
    } else {
        cell.group = self.group;
        cell.didClickUserBlock = ^(NSInteger index) {
            @strongify(self);
            [self didClickUserWithIndex:index];
        };
        [[[cell.lookMoreBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self didClickLookMoreUserBtnAction];
        }];
        [[[cell.deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self didClickDeleteUserAction];
        }];
        [[[cell.addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self didClickAddUserBtnAction];
        }];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YBContentModel *model = self.dataSource[indexPath.row];
//    if ([model.title isEqualToString:@"群聊名称"] == YES) {
//        [self didClickGroupNameCell];
//    }
//    else
    if ([model.title isEqualToString:@"群号和二维码"] == YES) {
        [self didClickGroupNumberCell];
    }
    else if ([model.title isEqualToString:@"群管理"] == YES) {
        [self didClickGroupManagerCell];
    }
    else if ([model.title isEqualToString:@"清空聊天记录"] == YES) {
        [self didClickCleanMsgCellAction];
    }
    else if ([model.title isEqualToString:@"查找聊天内容"] == YES) {
        [self didClickSearchGroupMsgCell];
    }
}

#pragma mark - actions
- (void)didClickUserWithIndex:(NSInteger)index {
    FriendItem *user = self.group.group_users[index];
    [self showFriendInfoVCWithType:2 friendItem:user from:@"0"];
}
- (void)showFriendInfoVCWithType:(NSInteger)type friendItem:(FriendItem *)item from:(NSString *)from {
    FriendInfoListVC *VC = [FriendInfoListVC new];
    VC.user = item;
    VC.from = from;
    VC.listType = type;
    
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)didClickLookMoreUserBtnAction {
    GroupUserListVC *listVc = [GroupUserListVC new];
    listVc.group = self.group;
    [self.navigationController pushViewController:listVc animated:YES];
}
- (void)didClickAddUserBtnAction {
    AddressListVC *addUserVC = [AddressListVC new];
    addUserVC.listType = 3;
    addUserVC.group = self.group;
    @weakify(self);
    [addUserVC setDidClickCreateGroupChatBlock:^(NSArray * _Nonnull ids) {
        @strongify(self);
        [self groupAddUsers:ids];
    }];
    BaseNavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:addUserVC];
    [self presentViewController:nv animated:YES completion:nil];
}
- (void)groupAddUsers:(NSArray *)userIdArr {
    
    NSMutableString *userids = [[NSMutableString alloc] init];
    for (NSString *uid in userIdArr) {
        [userids appendFormat:@"%@,",uid];
    }
    [userids deleteCharactersInRange:NSMakeRange(userids.length-1, 1)];
    @weakify(self);
    [MBProgressHUD showActivityMessageInView:@"添加联系人"];
    [[YBApiManager.shareManager addGroupUserWithUserIds:userids groupId:self.group.group_id] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        @strongify(self);
        [self requestDatas];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}
- (void)didClickDeleteUserAction {
    GroupUserListVC *deleteUserVC = [GroupUserListVC new];
    deleteUserVC.listType = 1;
    deleteUserVC.group = self.group;
    [deleteUserVC setDidClickDeleteGroupUserBlock:^(NSArray * _Nonnull ids) {
        [self groupDeleteUsers:ids];
    }];
    BaseNavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:deleteUserVC];
    [self presentViewController:nv animated:YES completion:nil];
}
- (void)groupDeleteUsers:(NSArray *)userIdArr {
    NSMutableString *userids = [[NSMutableString alloc] init];
    for (NSString *uid in userIdArr) {
        [userids appendFormat:@"%@,",uid];
    }
    [userids deleteCharactersInRange:NSMakeRange(userids.length-1, 1)];
    @weakify(self);
    [MBProgressHUD showActivityMessageInView:@"删除联系人"];
    [[YBApiManager.shareManager deleteGroupUserWithUserIds:userids groupId:self.group.group_id] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInView:@"操作成功" timer:1.0f];
        @strongify(self);
        [self requestDatas];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}
- (void)didClickBottomBtnAction:(UIButton *)sender {
    [LBXAlertAction showAlertWithTitle:@"提示" msg:@"确认退出？" buttonsStatement:@[@"取消", @"确认"] chooseBlock:^(NSInteger buttonIdx) {
        if (buttonIdx == 1) {
            [self quitGroupChatAction];
        }
    }];
}
- (void)quitGroupChatAction {
    [MBProgressHUD showActivityMessageInView:@"退出群聊"];
    [[YBApiManager.shareManager quitGroupWithgroup_id:self.group.group_id] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInWindow:@"退出成功" timer:1.0f];
        
        [MsgItem deleteWithWhere:@{@"group_id": self.group.group_id}];
        [SessionItem deleteWithWhere:@{@"group_id": self.group.group_id?:@""}];
        [kUsermanager updateGroupChatList];
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_DeleteGroupChat object:self.group];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)didClickGroupNumberCell {
    MyQRCodeVC *qrVC = [MyQRCodeVC new];
    
    qrVC.vcType = 1;
    qrVC.group = self.group;
    
    [self.navigationController pushViewController:qrVC animated:YES];
}
- (void)didClickGroupManagerCell {
    GroupManagerVC *managerVC = GroupManagerVC.new;
    managerVC.group = self.group;
    [self.navigationController pushViewController:managerVC animated:YES];
}

- (void)didClickSwitchViewAction:(UISwitch *)switchView indexPath:(NSIndexPath *)indexPath {
    YBContentModel *model = self.dataSource[indexPath.row];
    BOOL originValue = !switchView.isOn;
    @weakify(self);
    
    [[YBApiManager.shareManager updateGroupWithGroupId:self.group.group_id nickName:nil no_disturb:[NSString kk_stringWithInteger:!originValue]] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        model.selected =
        self.group.no_disturb = !originValue;
        [self.group updateToDB];
        [self.tableView reloadData];
        
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
        @strongify(self);
        [self.tableView reloadData];
    }];
}
- (void)didClickCleanMsgCellAction {
    [LBXAlertAction showAlertWithTitle:@"提示" msg:@"确定删除群的聊天记录吗？" buttonsStatement:@[@"取消", @"清空"] chooseBlock:^(NSInteger buttonIdx) {
        if (buttonIdx == 1) {
            [MBProgressHUD showActivityMessageInView:@"删除聊天记录..."];
            [Cache_Help cleanFilesWithGroupId:self.group.group_id];
            [MsgItem deleteWithWhere:@{@"group_id": self.group.group_id}];
            if (self.didCleanGroupMsgBlock) {
                self.didCleanGroupMsgBlock();
            }
            [MBProgressHUD hideHUD];
            [MBProgressHUD showTipMessageInView:@"删除完成" timer:1.0f];
        }
    }];
}
- (void)didClickSearchGroupMsgCell {
    SearchMsgVC *chatVC = SearchMsgVC.new;
//    chatVC.listType = 1;
    chatVC.group = self.group;
    [self.navigationController pushViewController:chatVC animated:YES];
}
@end
